package com.tuling.jucdemo.hashmap;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author :tangweiliang
 * @date : 2022/12/4 16:07
 * 未来的你会感谢现在努力的自己
 * <p>
 * UNSAFE 模拟线程安全问题
 */
public class Person {
    private int i = 0;
    private static long I_OFFSET;
    private static sun.misc.Unsafe UNSAFE;
    private String[] table = {"1","2","3","4"};

    static {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe"); // theUnsafe
            field.setAccessible(true);
            UNSAFE = (Unsafe) field.get(null);
            I_OFFSET = UNSAFE.objectFieldOffset(Person.class.getDeclaredField("i")); // 偏移量
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Person person = new Person();

        // 数组中存储的对象的对象头大小
        int ss = UNSAFE.arrayIndexScale(String[].class);
//        int ns = UNSAFE.arrayIndexScale(String[].class);
        // 数组中第一个元素的起始位置
//        int base = UNSAFE.arrayBaseOffset(String[].class);
//        System.out.println(UNSAFE.getObject(person.table,base+2*ns));
        int j = 3;
        System.out.println(j << (31 - Integer.numberOfLeadingZeros(ss)));
        System.out.println(j*ss);


//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                while (true) {
//                    //person.i++;
//                    boolean b = UNSAFE.compareAndSwapInt(person, I_OFFSET, person.i, person.i + 1); //cas操作 比较person.i的值是否相等   相等了再加1
//                    if (b) {
//                        System.out.println(UNSAFE.getIntVolatile(person, I_OFFSET));
//                    }
//                    try {
//                        Thread.sleep(500);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        }).start();
//
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                while (true) {
//                    //person.i++;
//                    boolean b = UNSAFE.compareAndSwapInt(person, I_OFFSET, person.i, person.i + 1); //cas操作 比较person.i的值是否相等   相等了再加1
//                    if (b) {
//                        System.out.println(UNSAFE.getIntVolatile(person, I_OFFSET));
//                    }
//                    try {
//                        Thread.sleep(500);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        }).start();


    }
}
